<template>
  <div class="login-container">
    <div class="login-left-part">
      <!-- <div class="login_logo">
                <img src="./img/logo.png" width="345" height="63" />
            </div> -->
    </div>
    <el-form
      ref="loginForm"
      v-show="isLogin === 'loginForm'"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="off"
      label-position="top"
    >
      <div class="title-container">
        <h3 class="title"><span>地方企业征信平台</span></h3>
      </div>
      <div class="lab">账 号</div>
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="账 号"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="off"
        />
      </el-form-item>
      <div class="lab">密 码</div>
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="pwd"
          ref="pwd"
          v-model="loginForm.password"
          :type="pwd"
          placeholder="密 码"
          name="password"
          autocomplete="off"
        />
        <span class="show-pwd" @click="showPwd('pwd')">
          <svg-icon :icon-class="pwd === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <div class="lab">验证码</div>
      <el-form-item prop="vc">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          style="width: 50%"
          ref="userCode"
          v-model="loginForm.vc"
          placeholder="验证码"
          type="text"
        >
        </el-input>
        <div class="code" @click="changeCode">
          <el-image
            style="height: 46px; width: 180px"
            :src="loginForm.url"
          ></el-image>
        </div>
      </el-form-item>
      <!-- <div class="remember_pwd">
        <el-checkbox v-model="isRePwd" @change="rePwd">
          <span class="nopwd f16">记住密码</span>
        </el-checkbox>
        <div class="nopwd" @click="resetPwd">忘记密码?</div>
      </div> -->
      <div style="text-align: center">
        <el-button
          class="lbtn"
          :loading="loading"
          type="primary"
          @click.native="handleLogin('loginForm')"
        >
          登录</el-button
        >
      </div>

      <!-- <div style="font-size: 12px; color: #97a8be; margin-top: 25%">
        淄博市发改委、市域治理指挥中心、大数据管理局、中国人民银行（淄博市中心支行)、淄博市地方金融监管局
      </div> -->
    </el-form>

    <!-- 忘记密码 -->
    <el-form
      ref="resetForm"
      v-show="isLogin === 'resetForm'"
      :model="resetForm"
      :rules="resetRules"
      class="login-form"
      autocomplete="off"
      label-position="left"
    >
      <div class="title-container">
        <h1 class="title">忘 记 密 码?</h1>
        <div class="f15" style="color: #7881ad; margin-bottom: 40px">
          Don't worryl Enter your registered mobile number to get password reset
          instructions.
        </div>
      </div>
      <div class="lab">手机号码</div>
      <el-form-item prop="userPhone">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="userPhone"
          v-model="resetForm.userPhone"
          placeholder="请输入手机号码"
          type="text"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item prop="userCode">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          style="width: 60%"
          v-model="resetForm.userCode"
          placeholder="请输入验证码"
          type="text"
          autocomplete="off"
        >
        </el-input>
        <el-button class="cbtn" v-if="!showTime" type="primary" @click="getCode"
          >获取验证码
        </el-button>
        <el-button class="cbtn" v-if="showTime" type="primary">
          {{ count }}
        </el-button>
      </el-form-item>
      <div class="ltxt">
        没有收到验证码? <span class="txt_span" @click="getCode">重新发送</span>
      </div>
      <el-button
        class="lbtn"
        :loading="loading"
        type="primary"
        @click.native.prevent="handleLogin('resetForm')"
        >完 成</el-button
      >
      <div class="ltxt" @click="isLogin = 'loginForm'">
        <span>还记得密码吗?</span><br />
        <svg-icon style="font-size: 25px" icon-class="back" /><span
          style="margin-left: 10px; cursor: pointer"
          >登录</span
        >
      </div>
    </el-form>

    <el-form
      ref="passForm"
      v-show="isLogin === 'passForm'"
      :model="passForm"
      :rules="passRules"
      class="login-form"
      autocomplete="off"
      label-position="left"
    >
      <div class="title-container">
        <h1 class="title">重 置 密 码?</h1>
        <div class="f15" style="color: #7881ad; margin-bottom: 40px">
          Please reset your login password.
        </div>
      </div>
      <div class="lab">输入密码</div>
      <el-form-item prop="rpassword">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="pwd1"
          ref="pwd1"
          v-model="passForm.rpassword"
          :type="pwd1"
          placeholder="请输入新密码"
          name="password"
          autocomplete="off"
        />
        <span class="show-pwd" @click="showPwd('pwd1')">
          <svg-icon :icon-class="pwd1 === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <div class="lab">确认密码</div>
      <el-form-item prop="rpassword1">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="pwd2"
          ref="pwd2"
          v-model="passForm.rpassword1"
          :type="pwd2"
          placeholder="请确认新密码"
          name="password"
          autocomplete="off"
        />
        <span class="show-pwd" @click="showPwd('pwd2')">
          <svg-icon :icon-class="pwd2 === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-button
        class="lbtn"
        :loading="loading"
        type="primary"
        @click.native.prevent="handleLogin('passForm')"
        >确 认</el-button
      >
      <div class="ltxt" @click="isLogin = 'passForm'">
        <span>还记得密码吗?</span><br />
        <svg-icon style="font-size: 25px" icon-class="back" /><span
          style="margin-left: 10px; cursor: pointer"
          >登录</span
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { login } from "@/api/login.js";
import { getAuth } from "@/utils/auth";

export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value && value.length < 5) {
        callback(new Error("密码不少于6位"));
      } else {
        callback();
      }
    };
    return {
      pwd: "password",
      pwd1: "password",
      pwd2: "password",
      loading: false,
      redirect: undefined,
      isLogin: "loginForm",
      /* 倒计时 */
      count: "",
      timer: null,
      showTime: false,
      /* 登录 系列*/
      loginForm: {
        username: "",
        password: "",
        vcToken: "",
        vc: "",
        url: "",
      },
      loginRules: {
        username: [
          {
            required: true,
            trigger: "blur",
            validator: validateUsername,
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            message: "请输入密码",
          },
        ],
        vc: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入验证码",
          },
        ],
      },
      /* 忘记密码系列 */
      isRePwd: false,
      resetForm: {},
      resetRules: {
        userPhone: [
          {
            required: true,
            trigger: "blur",
          },
        ],
        userCode: [
          {
            required: true,
            trigger: "blur",
          },
        ],
      },
      /* 重置密码系列 */
      passForm: {},
      passRules: {
        rpassword: [
          {
            required: true,
            trigger: "blur",
          },
        ],
        rpassword1: [
          {
            required: true,
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
        }
      },
      immediate: true,
    },
  },
  created() {
    //绑定事件
    let t = this;
    document.onkeydown = function (e) {
      let key;
      if (window.event == undefined) {
        key = e.keyCode;
      } else {
        key = window.event.keyCode;
      }
      //enter的ASCII码是13
      if (key == 13) {
        t.handleLogin("loginForm");
      }
    };
    /* 初始化表单 */
    let actPwd = localStorage.getItem("encryptionMd5");
    if (actPwd) {
      this.isRePwd = true;
      this.loginForm.username = "" || JSON.parse(actPwd).username;
      this.loginForm.password = "" || JSON.parse(actPwd).password;
    } else {
      this.isRePwd = false;
    }
  },
  destroyed() {
    document.onkeydown = "";
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
    this.getImgCode();
  },
  methods: {
    /* 获取图形验证码*/
    getImgCode() {
      let t = new Date().getTime();
      this.$axios
        .get(process.env.VUE_APP_BASE_API+"/b/privs/vc?t=" + t, {
          responseType: "blob",
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((data) => {
          this.loginForm.vcToken = data.headers.vctoken;
          let blobUrl = window.URL.createObjectURL(data.data);
          this.loginForm.url = blobUrl;
        })
        .catch(() => {
          this.$message.error("验证码获取超时!");
        });
    },
    changeCode() {
      this.getImgCode();
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd(e) {
      if (e == "pwd") {
        if (this.pwd == "password") {
          this.pwd = "";
        } else {
          this.pwd = "password";
        }
      } else if (e == "pwd1") {
        if (this.pwd1 == "password") {
          this.pwd1 = "";
        } else {
          this.pwd1 = "password";
        }
      } else {
        if (this.pwd2 == "password") {
          this.pwd2 = "";
        } else {
          this.pwd2 = "password";
        }
      }

      this.$nextTick(() => {
        this.$refs[e].focus();
      });
    },
    rePwd(e) {
      if (e) {
        let form = this.loginForm;
        localStorage.setItem("encryptionMd5", JSON.stringify(form));
      } else {
        localStorage.removeItem("encryptionMd5");
      }
    },
    /* 获取手机验证码 */
    getCode() {
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.showTime = true;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.showTime = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    handleLogin(e) {
      if (e == "passForm") {
        this.$refs.passForm.validate((valid) => {
          if (valid) {
            this.loading = false;
            this.$notify({
              title: "成功",
              message: "密码重置成功!请重新登录",
              type: "success",
            });
            this.isLogin = "loginForm";
          } else {
            let _this = this;
            setTimeout(() => {
              _this.loading = false;
            }, 1000);
            console.log("error submit!!");
            return false;
          }
        });
      } else if (e == "loginForm") {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            this.loading = true;
            let form = this.loginForm;
            login({
              username: form.username,
              password: form.password,
              vc: form.vc,
              vcToken: form.vcToken,
            }).then((data) => {
              if (data.status) {
                this.loading = false;
                localStorage.setItem("username", form.username);
                // 存储登录info
                this.$store.dispatch("user/login", {
                  username: form.username,
                  password: form.password,
                  token: data.data.token,
                  userType: data.data.userType,
                  roleId: data.data.roleId,
                });
                // 获取权限author
                this.$store.dispatch("user/getAuthor");
                this.$router.push({
                  path: "/manager",
                });
                /* 记住密码 */
                this.rePwd(this.isRePwd);
              } else {
                this.isRePwd = false;
                this.rePwd(this.isRePwd);
                this.loading = false;
                this.$message.error(data.msg);
                // 更新验证码
                this.getImgCode();
              }
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
        this.$refs.resetForm.validate((valid) => {
          if (valid) {
            this.loading = false;
            this.isLogin = "passForm";
          } else {
            let _this = this;
            setTimeout(() => {
              _this.loading = false;
            }, 1000);
            console.log("error submit!!");
            return false;
          }
        });
      }
    },
    /* 忘记密码 */
    resetPwd() {
      this.$refs.userPhone.focus();
      this.isLogin = "resetForm";
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #7881ad;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: #7881ad;
  }
}

.iconClass {
  background-color: #f0f9eb !important;
  border-color: #409eff !important;
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #7881ad;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid #eaeaea;
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #222653;
$dark_gray: #889aa4;
$light_gray: #3a3f63;

/deep/ .el-input__inner {
  &:focus {
    box-shadow: none !important;
  }
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  @include fj(center);
  align-items: center;
  overflow: hidden;

  /* 左侧海报 */
  // .login-left-part {
  //     @include wh(480px, 900px);
  //     background: url(img/login.png) no-repeat;
  //     background-size: 100% 100%;
  //     position: relative;

  //     .login_logo {
  //         position: absolute;
  //         left: 15px;
  //         top: 20px;
  //         line-height: 80px;
  //         color: #FFFFFF;
  //         @include fj(flex-start);
  //         font-size: 22px;
  //     }
  // }
  .login-form {
    position: relative;
    @include wh(920px, 900px);
    max-width: 100%;
    padding: 150px 170px 0 170px;
    background-color: #ffffff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .remember_pwd {
      line-height: 25px;
      @include fj(space-between);
    }

    .lab {
      color: #616582;
      margin-bottom: 5px;
    }

    .lbtn {
      width: 40%;
      margin: 25px 0;
      height: 50px;
      border-radius: 30px;
      background: linear-gradient(to bottom, #4186ff, #4b61ff);
    }

    .cbtn {
      height: 52px;
      width: 32%;
      float: right;
      background: linear-gradient(to bottom, #4186ff, #4b61ff);
    }

    .ltxt {
      color: #7881ad;
      font-size: 16px;
      line-height: 30px;
      font-weight: 550;

      .txt_span {
        cursor: pointer;
        font-size: 17px;
        color: #3a3f63;
        margin-left: 5px;
      }
    }

    .nopwd {
      font-weight: 600;
      color: #616582;
      text-align: center;
      cursor: pointer;
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .code {
    position: absolute;
    top: 2px;
    right: 0;
  }

  .title-container {
    position: relative;
    margin-bottom: 30px;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 10px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  @media only screen and (max-width: 900px) {
    .login-left-part {
      display: none;
    }

    .login-form {
      padding: 8%;
    }
  }

  @media only screen and (min-width: 0px) and (max-width: 600px) {
    .lbtn {
      width: 100% !important;
    }
  }
}
</style>
